/**
 * Created by wangfan on 2017/5/21.
 */

var editor; // use a global for the submit and return data rendering
var table;
var userTypeId=0;
var user;
var communityId="";

$(document).ready(function () {

    var url ="";
    $.ajax({
        url: '/commis/api/user/currentUser',
        type: "GET",
        async: false,
        dataType: 'json',
        data: {

        },
        success: function (response) {
            if (response.status==0) {
                console.log("用户存在");
                user =response.data;
                userTypeId=user.userTypeId;
                if(userTypeId==4){
                    communityId=user.communityId;
                    url = url + "&communityId=" + communityId;
                }else if(userTypeId==2){
                    communityId =getUrlParam("communityId");
                    if (communityId>0){

                        url = url + "&communityId=" + communityId;



                    }
                    var year =getUrlParam("year");
                    if(year>0){
                        url = url + "&attYear=" + year;
                        $('#year').val(year);

                    }
                    var month =getUrlParam("month");
                    if(month>0){
                        url = url + "&attMonth=" + month;
                        $('#month').val(month);
                    }
                }
                console.log(userTypeId);
            } else if (response.status==1) {
                alert("登录用户已经过期，请重新登录");
                window.parent.location.href = "../../login.html";
            }
        },error: function (msg) {
            alert("登录用户已经过期，请重新登录");
            window.parent.location.href = "../../login.html";
        }
    })

    $.ajax({
        url: '/commis/api/community/allCom',
        async: false,
        dataType: 'json',
        success: function (response) {
            console.log(response.length);
            for (var i = 0; i < response.length; i++) {
                $("#community").append("<option value='" + response[i].communityId + "'>" + response[i].communityName + "</option>");
            }

            $('#community').val(communityId);


        }, error: function () {

        }
    });



    $("#inputfile").fileinput({
        uploadUrl: "/commis/api/upload/uploadAttFile", // server upload action
        uploadAsync: true,
        showPreview: false,
        language: 'zh',
        uploadExtraData: {id: '${submission.missionId}'},
        maxFileCount: 1,
        elErrorContainer: ".file-error",
        allowedFileExtensions: ["xls", "xlsx"]
    }).on("fileuploaded", function (event, data, id, index) {
        var response = data.response;
        var status = response.status;
        var out;
        if (status == 0) {
            var fname = data.files[index].name;
            out = '上传文件  - ' +
                fname + ' 成功.';
            alert("上传成功");
        }

        else if (status == 1) {
            alert("上传失败");
        } else {
            out = '当月文件已经上传，请不要重复上传';
            alert("当月文件已经上传，请不要重复上传");

        }
        $('.file-success').html(out);
        $('.file-success').fadeIn('slow');
        // $('#inputfile').parent().prev().hide();


    }).on('fileclear', function (event) {
        $('#inputfile').val("");
        // $('#inputfile').parent().prev().show();
        $('.file-success').hide();

    });
    editor = new $.fn.dataTable.Editor({
        ajax: {
            create: {
                type: 'POST',
                url: '/commis/api/attendance/create'
            },
            edit: {
                type: 'PUT',
                url: '/commis/api/attendance/edit?id=_id_'
            },
            remove: {
                type: 'DELETE',
                url: '/commis/api/attendance/remove?id=_id_'
            }
        },
        i18n: {
            create: {
                title: "新增记录",
                submit: "添加"
            },
            edit: {
                title: "修改记录",
                submit: "修改",
                confirm: "您确定要修改这 %d 条记录吗?"
            },
            remove: {
                title: "删除记录",
                submit: "删除",
                confirm: "您确定要删除这 %d 条记录吗?"
            }
        },
        idSrc: 'attId',
        table: "#dataTable",
        fields: [
            {
                label: "事假:",
                name: "leaveAffairs"
            }, {
                label: "病假:",
                name: "leaveSick"
            }, {
                label: "年假:",
                name: "leaveYear"
            }, {
                label: "产假:",
                name: "leaveMaternity"
            }, {
                label: "婚假:",
                name: "leaveMarriage"
            } ,{
                label: "丧假:",
                name: "leaveFuneral"
            }
        ]
    });
    var buttons = [];
    var select = false;
    if (userTypeId == 1) {
        $("#communityDiv").show();
        select = true;
        buttons = [
            {extend: "edit", editor: editor, text: "修改", className: 'btn btn-primary'}
        ];
        console.log(buttons);


    } else if (userTypeId == 2) {
        $("#communityDiv").show();
        $("#sqjsSpan").show();
        select = false;
        buttons = [];

    } else if (userTypeId == 3||userTypeId == 6||userTypeId == 7||userTypeId == 8||userTypeId == 9) {
        $("#communityDiv").show();
        select = false;
        buttons = [];

    } else if (userTypeId == 4) {
        $("#communityDiv").hide();
        $("#fileDiv").show();
        $("#addDataDiv").show();
        select = false;
        buttons = []
    }else if (userTypeId == 5) {
        $("#communityDiv").show();
        select = false;
        buttons = [];

    }
    $('#startTime').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "year",
        autoclose: true,
        // todayBtn: true,


    });
    $('#endTime').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "year  ",
        autoclose: true,
        // todayBtn: true,


    });
     table =$('#dataTable').DataTable({
         dom: "Bfrtip",
        ajax: "/commis/api/attendance/pageDatatables?1=1"+url,
         autoWidth:true,
         responsive: true,
        serverSide: true,
        processing: true,
        lengthChange: false,//是否允许用户改变表格每页显示的记录数
        ordering: false,//是否允许用户排序
        paging: true,//是否分页
        pagingType: "full_numbers",//除首页、上一页、下一页、末页四个按钮还有页数按钮
        searching: false,//是否开始本地搜索
        language: {
            emptyTable: "没有数据",
            search: "搜索:",
            paginate: {
                first: "首页",
                previous: "上一页",
                next: "下一页",
                last: "尾页"

            },
            lengthMenu: "每页 _MENU_ 条记录",
            zeroRecords: "没有找到记录",
            info: "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )，共 _TOTAL_ 项",
            infoEmpty: "无记录",
            infoFiltered: "(从 _MAX_ 条记录过滤)"
        },
        columns: [
            {
                data: 'person.personName', defaultContent: ""

            },{
                data: 'person.community.communityName', defaultContent: ""

            }, {
                data: 'registerTime', defaultContent: ""
            }, {
                data: 'user.realName', defaultContent: ""
            }, {
                data: 'leaveAffairs', defaultContent: ""
            }, {
                data: 'leaveSick', defaultContent: ""
            }, {
                data: 'leaveYear', defaultContent: ""
            }, {
                data: 'leaveMaternity', defaultContent: ""
            }, {
                data: 'leaveMarriage', defaultContent: ""
            }, {
                data: 'leaveFuneral', defaultContent: ""
            }, {
                data: 'attYear', defaultContent: ""
            }, {
                data: 'attMonth', defaultContent: ""
            }],
         select: select,
         buttons: buttons

    });








})

$('#search').on('click', function () {

    var url = "/commis/api/attendance/pageDatatables?1=1"
    var communityId = $('#community').val();
    url = url + "&communityId=" + communityId;
    var year = $('#year').val();
    if (year != "") {
        if(isNaN(year)){
            toastr["warning"]("查询年份必须是4位数字");
            return false;
        }else{
            if(year.length!=4){
                toastr["warning"]("查询年份必须是4位数字");
                return false;

            }
        }
        url = url + "&attYear=" + year;
    }
    if ($("#month").val() != "") {
        var month = $('#month').val();
        url = url + "&attMonth=" + month;
    }
    if ($("#startTime").val() != "") {
        var startTime = $('#startTime').val();
        url = url + "&startTime=" + startTime;
    }
    if ($("#endTime").val() != "") {
        var startTime = $('#endTime').val();
        url = url + "&endTime=" + endTime;
    }


    table.ajax.url(url).load();
});

$('#confirm').on('click', function () {

    var url ="";
    var communityId = $('#community').val();
    if(communityId!=""){
        url = url + "&communityId=" + communityId;
    }else{
        toastr["warning"]("请选择对应社区");
        return false;
    }
    $.ajax({
        url: '/commis/api/attendance/alterFlag?flag=1'+url,
        type: "GET",
        async: false,
        dataType: 'json',
        data: {

        },
        success: function (response) {
            if (response.status==0) {
                toastr["success"]("成功");
                $.ajax({
                    url: '/commis/api/index/notify',
                    type: "GET",
                    async: false,
                    dataType: 'json',
                    success: function (result) {
                        if (result.status == 0) {
                            countNotify(result);
                        }


                    }, error: function (msg) {
                        alert("发生错误");
                    }
                })
                return false;
            } else if (response.status==1) {
                toastr["warning"]("失败");
            }
        },error: function (msg) {
            alert("发生错误");
        }
    })

});
$('#backButton').on('click', function () {

    var url ="";
    var communityId = $('#community').val();
    if(communityId!=""){
        url = url + "&communityId=" + communityId;
    }else{
        toastr["warning"]("请选择对应社区");
        return false;
    }
    $.ajax({
        url: '/commis/api/attendance/alterFlag?flag=0'+url,
        type: "GET",
        async: false,
        dataType: 'json',
        data: {

        },
        success: function (response) {
            if (response.status==0) {
                toastr["success"]("成功");
                $.ajax({
                    url: '/commis/api/index/notify',
                    type: "GET",
                    async: false,
                    dataType: 'json',
                    success: function (result) {
                        if (result.status == 0) {
                            countNotify(result);
                        }


                    }, error: function (msg) {
                        alert("发生错误");
                    }
                })
                return false;
            } else if (response.status==1) {
                toastr["warning"]("失败");
            }
        },error: function (msg) {
            alert("发生错误");
        }
    })

});
$("#btDownload").on('click', function () {

    // var url1 = "/commis/api/attendance/btDownload?1=1"
    var url ="";
    var year = $('#year').val();
    if (year != "") {
        if (isNaN(year)) {
            toastr["warning"]("年份必须是4位数字");
            return false;
        } else {
            if (year.length != 4) {
                toastr["warning"]("年份必须是4位数字");
                return false;

            }
        }
        url = url + "&year=" + year;
    }else {
        toastr["warning"]("请输入正确年份");
        return false;
    }
    if ($("#month").val() != "") {
        var month = $('#month').val();
        url = url + "&month=" + month;
    }else{
        toastr["warning"]("请选择月份");
        return false;
    }
    $.ajax({
        url: '/commis/api/attendance/isExist?1=1'+url,
        type: "GET",
        async: false,
        dataType: 'json',
        data: {

        },
        success: function (response) {
            if (response.status==0) {
                window.parent.location.href = "/commis/api/attendance/btDownload?1=1"+url;
            } else if (response.status==1) {
                alert("所选年月没有数据！");
            }
        },error: function (msg) {
            alert("发生错误");
        }
    })


});
//设置框架
$(function () {
    $("#page_style").frame({
        float: 'left',
        menu_nav: '.Quick_operation',
        color_btn: '.skin_select',
        Sellerber_menu: '.list_content',
        Sellerber_header: '.Sellerber_header',
    });
});
$("#iframe_box").niceScroll({
    cursorcolor: "#888888",
    cursoropacitymax: 1,
    touchbehavior: false,
    cursorwidth: "5px",
    cursorborder: "0",
    cursorborderradius: "5px"
});
/*********************/
require.config({
    paths: {
        echarts: './js/dist'
    }
});